<template>
  <view class="container">
    <view class="info">
      <view class="title">宿舍信息</view>
      <view class="room-layout">房间布局</view>
      <swiper class="swiper" indicator-dots="true" autoplay="true" interval="3000" circular="true">
        <swiper-item v-for="(item, index) in imgList" :key="index">
          <image :src="item" class="slide-image" mode="aspectFill"></image>
        </swiper-item>
      </swiper>
      <view class="item">
        <text class="label">空调：</text>
        <text class="value">{{ furnitureData.airConditioner||0 }}</text>
      </view>
      <view class="item">
        <text class="label">洗衣机：</text>
        <text class="value">{{ furnitureData.washingMachine||0 }}</text>
      </view>
      <view class="item">
        <text class="label">冰箱：</text>
        <text class="value">{{ furnitureData.refrigerator||0 }}</text>
      </view>
      <view class="item">
        <text class="label">吊风扇：</text>
        <text class="value">{{ furnitureData.fan||0 }}</text>
      </view>

    </view>
    <view class="rent">
      <view class="rent-value">
        <text class="label">租金：</text>
        <text class="value">{{ rentData||0 }}</text>
      </view>
    </view>
    <button class="button" @click="handleMoveIn">入住</button>
  </view>
</template>

<script>
  import {
    ajax
  } from '../../utils/request';

  export default {
    data() {
      return {
        furnitureData: {
          refrigerator: '1',
          airConditioner: '1',
          washingMachine: '1',
          fan: '1',
        },
        rentData: '￥3000/月', // 默认租金值
        imgList: [
          '/static/图标/09热水花洒.png',
          '/static/图标/08设备录入.png',
          '/static/图标/06健身器材.png'
        ]
      };
    },
    onShow() {
      const roomInfo = uni.getStorageSync('selectedRoomInfo');
      if (roomInfo) {
        this.furnitureData.refrigerator = roomInfo.asset1;
        this.furnitureData.airConditioner = roomInfo.asset2;
        this.furnitureData.washingMachine = roomInfo.asset3;
        this.furnitureData.fan = roomInfo.asset4;
        this.rentData = roomInfo.rentMone; // 更新租金数据
        this.imgList = [roomInfo.assetimages1, roomInfo.assetimages2, roomInfo.assetimages3]; // 更新图片列表
      }
    },
    methods: {
      // 入住按钮点击事件
      handleMoveIn() {
        const roomInfo = uni.getStorageSync('selectedRoomInfo');
        if (!roomInfo) {
          uni.showToast({
            title: '请先选择房间',
            icon: 'none',
          });
          return;
        }
        // 计算支付金额
        const rentMone = Number(roomInfo.rentMoney);
        const depositMoney = Number(roomInfo.depositMoney);
        const totalFee = rentMone + depositMoney;

        // 调用微信支付接口
        // this.handleWechatPay(totalFee);
        this.submitRoomInfoAfterPayment();
      },

      // 调用微信支付接口
      handleWechatPay(total_fee) {
        uni.login({
          provider: 'weixin',
          success: (loginRes) => {
            if (loginRes.code) {
              console.log('获取到的 code: ' + loginRes.code);
              console.log('total_fee: ' + total_fee);
              ajax('/api/wxpay/rentpaywx', 'POST', {
                  code: loginRes.code,
                  total_fee,
                })
                .then((data) => {
                  console.log(data.msg);
                  uni.requestPayment({
                    provider: 'wxpay',
                    timeStamp: String(data.msg.TimeStamp),
                    nonceStr: data.msg.nonce_str,
                    package: "prepay_id=" + data.msg.responseObject.xml
                      .prepay_id._cdata + "",
                    signType: 'MD5',
                    paySign: data.msg.sign,
                    success: (res) => {
                      console.log('支付成功:', res);
                      uni.showToast({
                        title: '支付成功',
                        icon: 'success'
                      });

                      // 支付成功后提交入住信息
                      this.submitRoomInfoAfterPayment();
                    },
                    fail: (err) => {
                      console.log('支付失败:', err);
                      uni.showToast({
                        title: '支付失败',
                        icon: 'none'
                      });
                    }
                  });
                })
                .catch((error) => {
                  console.error('支付接口请求失败:', error);
                  uni.showToast({
                    title: '支付请求失败',
                    icon: 'none'
                  });
                });
            } else {
              console.log('登录失败！' + loginRes.errMsg);
              uni.showToast({
                title: '登录失败',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            console.log('调用登录接口失败', err);
            uni.showToast({
              title: '调用微信支付失败',
              icon: 'none'
            });
          }
        });
      },

      // 支付成功后提交入住信息
      submitRoomInfoAfterPayment() {
        const userInfo = uni.getStorageSync('userInfo');
        const roomInfo = uni.getStorageSync('selectedRoomInfo');
        const formData = uni.getStorageSync('formData');
        ajax('/api/meter/ssinfosubmit', 'POST', {
          ss_mc: roomInfo.ss_mc, // 替换为实际的房间ID
          account: userInfo.account,
          roomInfo: roomInfo, // 替换为实际的学工号
          formData: formData,
        }).then((res) => {

          console.log("提交入住信息成功", res);
          // 更新 userInfo 中的 ss_mc 字段
          userInfo.ss_mc = roomInfo.ss_mc; // 直接更新 ss_mc 字段
          uni.setStorageSync('userInfo', userInfo); // 重新存储 userInfo 到本地
          uni.showToast({
            title: '入住信息提交成功',
            icon: 'success'
          });
          // 跳转到首页
          uni.switchTab({
            url: '/pages/index/index'
          });
        }).catch((err) => {
          // 提交入住信息失败
          uni.showToast({
            title: '提交入住信息失败',
            icon: 'error',
          });
        });
      }
    }
  };
</script>

<style scoped>
  .container {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    background-color: #f2f2f2;
    min-height: 100vh;
  }

  .info {
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
  }

  .title {
    font-size: 15px;
    font-weight: bold;
    margin-bottom: 15px;
    text-align: center;
    color: #333;
  }

  .room-layout {
    font-size: 15px;
    font-weight: bold;
    font-weight: bold;
    margin-bottom: 10px;
    text-align: left;
  }

  .item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    padding: 10px 0;
    border-bottom: 1px solid #e0e0e0;
  }

  .label {
    min-width: 80px;
    text-align: justify;
    text-align-last: justify;
    color: #555;
    font-weight: bold;
    font-size: 15px;
  }

  .value {
    margin-left: 10px;
    color: #666;
    flex: 1;
    font-size: 15px;
  }

  .swiper {
    width: 100%;
    height: 200px;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;

  }

  .slide-image {
    width: 100%;
    height: 100%;
    background-color: red;
  }

  .rent {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 100%;
    margin-top: 20px;
    padding: 10px 0;
  }

  .rent-value {
    display: flex;
    align-items: center;
  }

  .rent-value .label {
    margin-right: 10px;
    color: #333;
    font-weight: bold;
    font-size: 15px;
  }

  .rent-value .value {
    color: #ff5a00;
    font-size: 15px;
    font-weight: bold;
  }

  .button {
    width: 120px;
    height: 45px;
    line-height: 45px;
    text-align: center;
    background-color: #2ba245;
    color: #fff;
    border-radius: 12px;
    font-size: 15px;
    margin-top: 20px;
    box-shadow: 0 4px 8px rgba(0, 122, 255, 0.2);
    transition: background-color 0.3s ease;
  }

  .button:hover {
    background-color: #005bb5;
  }
</style>